﻿using System;
using JTG.ServiceInterface.Attribute;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Tzw.Common;
using Tzw.Common.Model;

namespace JTG.ServiceInterface.InterfaceService
{
    /// <summary>
    /// 打印接口服务类(用于调用403/405打印机接口，读取打印机状态)
    /// 1、检测打印机是否连接
    /// 2、检测打印机状态是否准备准备就绪
    /// 3、检测打印机墨粉容量
    /// </summary>
    [FunctionName(FunctionType.HP405)]
    public class PrinterServiceHp405 : IPrinterService
    {
        private static string _url = ConfigurationManager.AppSettings["PrintApiUrl"];

        /// <summary>
        /// 查询打印机列表信息
        /// </summary>
        public List<PrinterInfo> GetList()
        {
            var respStr = HttpHelper.HttpGet(_url + "/devices");

            var printerInfos = JsonConvert.DeserializeObject<Printers>(respStr).PrinterInfos.Where(x => x.Online).ToList();
            for (var i = printerInfos.Count - 1; i > -1; i--)
            {
                //读取打印机状态
                GetStatus(printerInfos[i]);
                //移除不是打印中和未就绪的打印机
                if (printerInfos[i].Status != 1 && printerInfos[i].Status != 2)
                    printerInfos.RemoveAt(i);
            }

            return printerInfos;
        }

        /// <summary>
        /// 查看打印机状态
        /// </summary>
        /// <returns></returns>
        public void GetStatus(PrinterInfo printInfo)
        {
            // 打印机状态：
            // trayEmpty:缺纸
            // ready:就绪
            // processing:打印中
            // inPowerSave:节能模式
            // closeDoorOrCover:打印机门打开
            var respStr = HttpHelper.HttpGet(_url + $"/status/device/{printInfo.PortName}");

            if (respStr.Contains("ready")) //就绪
            {
                printInfo.Status = 1;
            }
            else if (respStr.Contains("processing")) //打印中
            {
                printInfo.Status = 2;
            }
            else
            {
                printInfo.Status = 0;
            }
        }

        /// <summary>
        /// 检测打印机墨粉容量（目前只检测黑色（K）墨粉的容量）
        /// </summary>
        /// <returns></returns>
        public void GetTonerVolume(PrinterInfo printInfo)
        {
            var respStr = HttpHelper.HttpGet(_url + $"/status/consumable/{printInfo.PortName}");
            var joList = JsonConvert.DeserializeObject<List<JObject>>(respStr);

            foreach (var jo in joList)
            {
                if (jo.Value<string>("ConsumableLabelCode") == "K")
                    printInfo.KV = jo.Value<int>("ConsumablePercentageLevelRemaining");
            }
        }
    }
}